<template>
  <div class="balance">
    <mt-header title="会员卡余额">
      <router-link to="/user" slot="left">
        <mt-button icon="back"></mt-button>
      </router-link>
    </mt-header>
    <div class="ref-header">
      <div class="ref-top1">会员卡余额</div>
      <div class="ref-top2">￥<span>{{balance}}</span></div>
      <button class="sign-btn" @click="chongzhi">充值</button>
    </div>
    <mt-actionsheet
      :actions= "sheetData"
      v-model="sheetVisible">
    </mt-actionsheet>
    <div>
      <mt-cell v-for="(item, index) of list" :key="index" class="border-bottom" :label="item.date" :title="item.memo">
        <span :style="item.status===1?'color: green':'color: red'">{{item.money}}</span>
      </mt-cell>
    </div>
  </div>
</template>

<script>
import { MessageBox, Toast } from 'mint-ui'
import axios from 'axios'
export default {
  name: 'CartBalance',
  data () {
    return {
      point: '',
      type: {
        typeId: '',
        typeName: '',
        typePrice: ''
      },
      weiXin: {
        appId: '',
        timeStamp: '',
        nonceStr: '',
        packageWeixin: '',
        paySign: ''
      },
      list: [],
      sheetData: [{
        name: '微信',
        method: this.wechatpay // 调用methods中的函数
      }, {
        name: '支付宝',
        method: this.alipay // 调用methods中的函数
      }, {
        name: '余额',
        method: this.balance // 调用methods中的函数
      }],
      sheetVisible: false
    }
  },
  methods: {
    getInfo () {
      if (this.$route.query.type === 'grass' || this.$route.query.type === 'peony' || this.$route.query.type === 'slverflower' || this.$route.query.type === 'goldenflower') {
        this.type.typeId = this.$route.query.type
        if (this.$route.query.type === 'grass') {
          this.type.typeName = '种草'
          this.type.typePrice = 399
        }
        if (this.$route.query.type === 'slverflower') {
          this.type.typeName = '银花'
          this.type.typePrice = 5000
        }
        if (this.$route.query.type === 'goldenflower') {
          this.type.typeName = '金花'
          this.type.typePrice = 20000
        }
        if (this.$route.query.type === 'peony') {
          this.type.typeName = '牡丹'
          this.type.typePrice = 50000
        }
        MessageBox.alert('您选择' + this.type.typeName + '需要支付' + this.type.typePrice).then(action => {
          this.sheetVisible = true
        })
      }
      axios.get('/meimai/interface/member/getMemberCardBalanceRecord', {
        params: {
          memberId: this.$store.state.userId
        }
      }).then((res) => {
        // console.log(res)
        let datas = res.data
        if (datas.code === 0) {
          this.balance = datas.balance
          this.list = datas.array
        }
      })
    },
    chongzhi () {
      this.sheetVisible = true
    },
    wechatpay () {
      if (!this.type.typeId) {
        MessageBox.prompt('请输入充值金额').then(({ value, action }) => {
          if (value && value === 0) {
            Toast('请输入正确的金额')
          }
          this.handlePay(value, 2)
        })
      } else {
        this.handlePay(this.type.typePrice, 2)
      }
    },
    alipay () {
      if (!this.type.typeId) {
        MessageBox.prompt('请输入充值金额').then(({ value, action }) => {
          if (value && value === 0) {
            Toast('请输入正确的金额')
          }
          this.handlePay(value, 3)
        })
      } else {
        this.handlePay(this.type.typePrice, 3)
      }
    },
    balance () {
      if (!this.type.typeId) {
        MessageBox.prompt('请输入充值金额').then(({ value, action }) => {
          if (value && value === 0) {
            Toast('请输入正确的金额')
          }
          this.handlePay(value, 4)
        })
      } else {
        this.handlePay(this.type.typePrice, 4)
      }
    },
    isWeixinBrowser () {
      let ua = navigator.userAgent.toLowerCase()
      return !!(/micromessenger/.test(ua))
    },
    handlePay (value, payId) {
      let wxPayType = ''
      if (this.isWeixinBrowser()) {
        wxPayType = 'JSAPI'
      } else {
        wxPayType = 'MWEB'
      }
      axios.get('/meimai/interface/member/recharge', {
        params: {
          memberId: this.$store.state.userId,
          money: value,
          payTypeId: payId,
          wxPayType: wxPayType
        }
      }).then((res) => {
        if (payId === 2) {
          // window.location.href = res.data.payUrl
          // console.log(res)
          if (this.isWeixinBrowser()) {
            this.weiXin.appId = res.data.appId
            this.weiXin.timeStamp = res.data.timeStamp
            this.weiXin.nonceStr = res.data.nonceStr
            this.weiXin.packageWeixin = res.data.package
            this.weiXin.paySign = res.data.paySign
            if (typeof WeixinJSBridge === 'undefined') {
              if (document.addEventListener) {
                document.addEventListener('WeixinJSBridgeReady', this.onBridgeReady, false)
              } else if (document.attachEvent) {
                document.attachEvent('WeixinJSBridgeReady', this.onBridgeReady)
                document.attachEvent('onWeixinJSBridgeReady', this.onBridgeReady)
              }
            } else {
              this.onBridgeReady()
            }
          } else {
            const div = document.createElement('div') // 创建div
            div.innerHTML = res.data.payUrl // 将返回的form 放入div
            document.body.appendChild(div)
            document.forms[0].submit()
            // window.location.href = res.data.payUrl
          }
        }
        if (payId === 3) {
          const div = document.createElement('div') // 创建div
          div.innerHTML = res.data.payUrl // 将返回的form 放入div
          document.body.appendChild(div)
          document.forms[0].submit()
        }
        if (payId === 4) {
          if (res.data.code === 0) {
            Toast({
              message: '充值成功',
              iconClass: 'iconfont icon-chenggong icon-font36'
            })
          } else {
            Toast({
              message: res.data.msg,
              iconClass: 'iconfont icon-shibai1 icon-font36'
            })
          }
        }
      })
    },
    onBridgeReady (appId, timeStamp, nonceStr, packageWexin, paySign) {
      WeixinJSBridge.invoke(
        'getBrandWCPayRequest',
        {
          'appId': this.weiXin.appId, // 公众号名称，由商户传入
          'timeStamp': this.weiXin.timeStamp, // 时间戳，自1970年以来的秒数
          'nonceStr': this.weiXin.nonceStr, // 随机串
          'package': this.weiXin.packageWeixin,
          'signType': 'MD5', // 微信签名方式
          'paySign': this.weiXin.paySign // 微信签名
        },
        function (res) {
          if (res.err_msg === 'get_brand_wcpay_request:ok') {
            // 使用以上方式判断前端返回,微信团队郑重提示：
            // res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
            Toast('支付成功')
          } else if (res.err_msg === 'get_brand_wcpay_request:cancel') {
            Toast('取消支付')
          } else {
            Toast('支付失败')
          }
        }
      )
    }
  },
  mounted () {
    this.getInfo()
  }
}
</script>

<style lang="stylus" scoped>
.mint-header
  background: #e00000
.ref-header
  width: 100%
  height: 3rem
  padding: 0.2rem
  overflow: auto
  background: #ec2935
  text-align: center
  color: #fff
  .ref-top1
    font-size: .4rem
    line-height: .8rem
  .ref-top2
    font-size: .3rem
    line-height: .6rem
    span
      font-size: .5rem
  .sign-btn
    width: 2.8rem
    height: .8rem
    line-height: .8rem
    text-align: center
    color: #fff
    border-radius: .8rem !important
    font-size: .5rem
    margin: .2rem auto 0 auto
    background-color: #f79500
</style>
